package com.wocao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wocao.entity.SysUser;
import com.wocao.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 自定义登录逻辑
 */
@Service
public class SysUserDetailsServiceImpl implements UserDetailsService {


    @Resource
    private SysUserService sysUserService;

    /**
     * 通过用户名查询用户
     * @param username
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username){
        //按用户名查询用户
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, username));
        if(user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        if (user.getStatus().equals("1")){
            throw new RuntimeException("账号已被停用");
        }
        if (user.getDelFlag().equals("2")){
            throw new RuntimeException("账号不存在");
        }
        //查询授权集合
        List<GrantedAuthority> authorities = sysUserService.getAuthoritiesByUsername(username);
        //将用户信息和授权包装到User对象中返回给Security
        return new org.springframework.security.core.userdetails.User(
                user.getUserName(),
                user.getPassword(),
                authorities);
    }
}
